package com.test.google.app.common;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.test.google.app.domain.File;
import com.test.google.app.service.FileService;
import com.test.google.app.service.impl.FileServiceImpl;
import com.test.google.app.util.GaeMemcacheUtil;

public class FileViewFilter implements Filter {
	
	private static Log log = LogFactory.getLog(FileViewFilter.class);
	
	private FileService fs = new FileServiceImpl();

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		
		String filePath = getFileName(request);
		if (filePath.equals("")) {
			arg2.doFilter(arg0, arg1);
		} else {
			Object o = GaeMemcacheUtil.get(filePath);
			if (o != null) {
				viewFile(response, (File)o);
				return;
			} else {
				List<File> list = fs.getByPath(filePath);
				if (list.isEmpty()) {
					log.warn("Can't find file: " + filePath);
					arg2.doFilter(arg0, arg1);
				} else {
					File file = list.get(0);
					GaeMemcacheUtil.put(file.getPath(), file, SysSetting.FILE_TTL);
					viewFile(response, file);
					return;
				}
			}
		}
	}

	private void viewFile(HttpServletResponse response, File file)
			throws IOException {
		response.setContentType(file.getMimeType() + ";");
		response.setHeader("Content-Disposition","inline");
		ServletOutputStream out = response.getOutputStream();
		out.write(fs.getContentByKey(file.getKey()));
		if (file.getPath().endsWith(".html") || file.getPath().endsWith(".htm")) {
			out.write(SysCfg.ADVERTISEMENT.getBytes());
		}
		out.close();
	}

	private String getFileName(HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		if (requestURI.contains("/haottiis")) {
			return "";
		} 
		String filePath = requestURI.toLowerCase().split(";")[0].trim();
		if (filePath.equals("/")) {
			filePath = "/index.html";
		}
		return filePath;
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

}
